package manager


import activity.InfoActivity
import activity.MainActivity
import activity.ScanActivity
import activity.SettingActivity
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.view.inputmethod.InputMethodManager
import app.AppContext
import ext.log
import ext.toMacAddress
import serialport.DeliverPortManager
import service.ResetService
import task.RefreshSellTask
import task.StatusWith3UploadTask
import task.UpdateTempValueTask
import java.io.PrintWriter
import java.net.NetworkInterface
import java.util.*

object AppManager : Runnable {

    const val TEST_SERVER_URL = "http://test.hontech-rdcenter.com:8080/bg-uc"
    const val SERVER_URL = "http://hfrd.hontech-rdcenter.com:8080/hontechgroup"

    const val TEST_PAY_WEB_URL = "http://www.hontech-rdcenter.com/testSjgl/transfer.html"
    const val PAY_WEB_URL = "http://www.hontech-rdcenter.com/testSjgl/transfer1.html"

    private const val DEFAULT_MAC = "00:18:05:0c:53:cf"
    private const val DEFAULT_URL = TEST_PAY_WEB_URL

    const val PORT1 = "/dev/ttymxc1"
    const val PORT2 = "/dev/ttymxc2"
    const val PORT3 = "/dev/ttymxc3"

    const val DAY_TIME = 1000 * 60 * 60 * 24

    const val CLEAR_CARGO_IF_FAIL = false // 出货失败的时候 是否需要封锁库存

    private const val DELIVER_PORT_KEY = "deliver.port.key"
    private const val ADVERTISING_KEY = "advertising.key"
    private const val SERVER_URL_KEY = "server-.-key"
    private const val INVENTROY_KEY = "inventory.key"
    private const val REPORT_KEY = "report.key"
    private const val MDB_PORT_KEY = "mdb.port.key"

//    private val DELIVER_PORT_DEFAULT_NAME =
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
//            "/dev/ttyS3"
//        else
//            "/dev/ttymxc2"

    /**
     * 东莞版本
     */
    private const val DELIVER_PORT_DEFAULT_NAME = "/dev/ttymxc2"

    private const val MDB_PORT_DEFAULT_NAME = "/dev/ttymxc1"

    val imm = AppContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

    private val sharedPreferences = AppContext.getSharedPreferences("sp.inventory", Context.MODE_PRIVATE)

    val Version = AppContext.packageManager.getPackageInfo(AppContext.packageName, 0).versionName

    val VersionCode = AppContext.packageManager.getPackageInfo(AppContext.packageName, 0).versionCode

    var isBusy = false

    var report = sharedPreferences.getString(REPORT_KEY, "")
        set(value) {
            if (value != field) {
                field = value
                sharedPreferences.edit().putString(REPORT_KEY, value).apply()
            }
        }

    var baseUrl = sharedPreferences.getString(SERVER_URL_KEY, DEFAULT_URL)
        set(value) {
            if (value != field) {
                field = value
                sharedPreferences.edit().putString(SERVER_URL_KEY, value).apply()
            }
        }

    var inventory = sharedPreferences.getString(INVENTROY_KEY, "") // 商品缓存
        set(value) {
            if (value != field) {
                field = value
                sharedPreferences.edit().putString(INVENTROY_KEY, value).apply()
            }
        }

    var advertising = sharedPreferences.getString(ADVERTISING_KEY, "") // 广告缓存
        set(value) {
            if (value != field) {
                field = value
                sharedPreferences.edit().putString(ADVERTISING_KEY, value).apply()
            }
        }

    var deliverPortName = sharedPreferences.getString(DELIVER_PORT_KEY, DELIVER_PORT_DEFAULT_NAME)
        set(value) {
            if (value != field) {
                field = value
                sharedPreferences.edit().putString(DELIVER_PORT_KEY, value).apply()
            }
        }

    var mdbPortName = sharedPreferences.getString(MDB_PORT_KEY, MDB_PORT_DEFAULT_NAME)
        set(value) {
            if (value != field) {
                field = value
                sharedPreferences.edit().putString(MDB_PORT_KEY, value).apply()
            }
        }

    var PayWebUrl = "http://www.hontech-rdcenter.com/testSjgl/transfer.html"
        get() {
            if (baseUrl == SERVER_URL) {
                return PAY_WEB_URL
            } else {
                return TEST_PAY_WEB_URL
            }
        }

    fun faultByCargo(cargo: String) = sharedPreferences.getBoolean("cargo:$cargo", false)
    fun clearFaultByCargo(cargo: String) = sharedPreferences.edit().putBoolean("cargo:$cargo", false).apply()
    fun setFaultByCargo(cargo: String) = sharedPreferences.edit().putBoolean("cargo:$cargo", true).apply()

    fun clearAllFault() {
        log("清除所有货道异常")
        for (row in 1 until 10) {
            for (col in 1 until 10) {
                clearFaultByCargo("$row-$col")
            }
        }
    }

    val MacAddress = getLocalEthernetMacAddress()
    val MacAddressTopic = MacAddress.replace(":", "")

    init {
        log(baseUrl, "服务器地址")
        log(advertising, "广告")
        log(inventory, "库存")
        log(report, "销量")
        log(mdbPortName, "MDB串口")
        log(deliverPortName, "出货串口")
        log(MacAddress, "MAC地址")
    }

    private fun getLocalEthernetMacAddress(): String {
        try {
            val interfaces = NetworkInterface.getNetworkInterfaces()
            interfaces.iterator().forEach {
                if (it.name == "eth0") {
                    return it.hardwareAddress.toMacAddress()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return DEFAULT_MAC
    }

    fun initApp() {
        StatusManager.Signal = 0
        TaskManager.UiHandler.post { } // 初始化UI Handler
        TaskManager.DelayHandler.post(RefreshSellTask()) // 刷新是否停售
        TaskManager.DelayHandler.post(CpuManager) // CPU使用率监听
        TaskManager.DelayHandler.post(StatusWith3UploadTask()) // 每隔3分钟发送一次状态
        HeatManager.refreshAsync() // 启动温度控制
        TaskManager.DelayHandler.post(UpdateTempValueTask()) // 获取温度报警值
        WaresManager.refreshAsync() // 刷新商品库存
        AdvertisingManager.refreshWithAsync() // 刷新广告
        MQTTManager.connectToServer() // 连接MQTT
        DeliverPortManager.Instance.start() // 启动串口
    }

    override fun run() {
    }

    fun resetSystem() {
        val s = arrayOf("su", "-c", "reboot")

        try {
            Runtime.getRuntime().exec(s).waitFor()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //fun closeSystem()
    //{
    //    val s = arrayOf("su", "-c", "reboot -p")
    //    try {
    //        Runtime.getRuntime().exec(s).waitFor()
    //    } catch (e: Exception) {
    //        e.printStackTrace()
    //    }
    //}

    fun installApk(path: String) {
        log("开始安装:$path")
        val prcess = Runtime.getRuntime().exec("su")
        val pw = PrintWriter(prcess.outputStream)
        pw.println("pm install -r $path")
        pw.flush()
        pw.close()
        val v = prcess.waitFor()
        log("安装返回值:$v")
    }

    fun checkApplication() {
        val msg =
            "Main:${MainActivity.isShow},Set:${SettingActivity.isShow},Scan:${ScanActivity.isShow},Info:${InfoActivity.isShow}"
        log(msg, "检测app状态")
        if ((!MainActivity.isShow) && (!SettingActivity.isShow) && (!ScanActivity.isShow) && (!InfoActivity.isShow)) {
            resetApp()
            return
        }
    }

    fun resetApp() {
        log("开始重启App")

        val i = Intent(AppContext, MainActivity::class.java)
        i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        val pi = PendingIntent.getActivity(AppContext, 0, i, 0)
        val am = AppContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 500, pi)

        android.os.Process.killProcess(android.os.Process.myPid())
    }


    fun setResetSystem() {
        val target = Calendar.getInstance()
        target.set(Calendar.HOUR_OF_DAY, 3)
        target.set(Calendar.MINUTE, 0)
        target.set(Calendar.SECOND, 0)
        val targetTime = target.timeInMillis

        val currentTime = Calendar.getInstance().timeInMillis
        val am = AppContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(AppContext, ResetService::class.java)
        val pi = PendingIntent.getService(AppContext, 0, intent, 0)

        val resetTime = if (targetTime > currentTime) targetTime else targetTime + DAY_TIME
        log("重启时间：$resetTime")

        am.set(AlarmManager.RTC_WAKEUP, resetTime, pi)
    }

}
